package com.example.area.io.netty.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author kancy
 * @date 2019/2/23 13:50
 */
@Slf4j
public class ServerHandler extends Thread {
	private Socket socket;
	public ServerHandler(Socket socket) {
		this.socket = socket;
	}
	@Override
	public void run() {
		if(socket == null ) return;
		BufferedReader in = null;
		PrintWriter out = null;
		try{
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);

			String line = null;
			while(true){
				// 读取数据
				line = in.readLine();
				log.info("服务端接受的信息：" + line);
				if("bye".equals(line)){
					break;
				}

				// 返回数据
				System.out.println("请输入返回数据：");
				Scanner sc  = new Scanner(System.in);
				line = sc.nextLine();
				out.println(line);
				if("bye".equals(line)){
					break;
				}
			}

		}catch (Exception e){
			log.error(e.getMessage(), e);
		}finally {
			closeResource(in, out);
			closeSocket();
		}
	}

	private void closeSocket() {
		if(socket != null){
			try {
				if(!socket.isClosed()){
					socket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		log.info("服务端关闭连接!");
		socket = null; // help gc
	}

	private void closeResource(Reader in, Writer out) {
		try {
			if (in != null){
				in.close();
				in = null; // help gc
			}
			if (out != null){
				out.close();
				out = null; // help gc
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
